package com.truyentranh.requester;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.truyentranh.data.HaiBLMetalData;
import com.truyentranh.data.HaiBLModule;
import com.truyentranh.data.TipData;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.network.UrlHelper;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.Logger;

public class UpdateRequester extends Request{
	
	private RequestListener requestListener;	
	
	public UpdateRequester(RequestListener listener){
		this.requestListener = listener;
	}
	
	@Override
	public void cancelRequest() {
		// TODO Auto-generated method stub		
	}

	@Override
	public void runRequest() {
		// TODO Auto-generated method stub
		url = UrlHelper.getUrlOfRequestUpdates(UrlHelper.BASE_URL_UPDATES);
		send();
	}	
	
	private int version = -1;
	private boolean force = false;
	private String message = "";
	private String link ="";
	private String detail = "";	
	
	private TipData tipdata;
	
	@Override
	public void requestFinished(JSONObject jsonObject) {
		
		if(jsonObject != null){
			try {
				version = jsonObject.has("version") ? jsonObject.getInt("version") : -1;
				force = jsonObject.has("force") ? jsonObject.getInt("force") == 1 : false;
				message = jsonObject.has("message") ? jsonObject.getString("message") : "";
				link = jsonObject.has("link") ? jsonObject.getString("link") : "";
				detail = jsonObject.has("detail") ? jsonObject.getString("detail") : "";	
				
				JSONObject tip = jsonObject.has("tip") ? jsonObject.getJSONObject("tip") : null;
				if(tip != null){
					String message = tip.has("message") ? tip.getString("message") : "";	
					String linkDetail = tip.has("link") ? tip.getString("link") : "";
					boolean isActive =  tip.has("active") ? (tip.getInt("active") == 1 ? true : false) : false;
					if(isActive){
						tipdata = new TipData(isActive, message, linkDetail);
					}					
				}
				
				if(requestListener != null){
					requestListener.onRequestComplete(this);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void requestFailed(int errorCode, String message) {
		// TODO Auto-generated method stub
		if(requestListener != null){
			requestListener.onRequestFailed(message, this);
		}
	}

	public int getVersion() {
		return version;
	}

	public String getMessage() {
		return message;
	}
	
	public boolean isForce() {
		return force;
	}
	
	public String getLink() {
		return link;
	}

	public String getDetail() {
		return detail;
	}

	public TipData getTipdata() {
		return tipdata;
	}

	public void setTipdata(TipData tipdata) {
		this.tipdata = tipdata;
	}

}
